package io.github.wslxm.springbootplus2.manage.sys.handle;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.github.wslxm.springbootplus2.manage.sys.dao.*;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysAuthority;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysMenu;
import io.github.wslxm.springbootplus2.manage.sys.model.entity.SysRole;
import io.github.wslxm.springbootplus2.manage.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 初始化超管账号权限 处理器
 *
 * @author 王松
 * @mail 1720696548@qq.com
 * @date 2025/9/23 9:13
 */
@Component
@Slf4j
public class InitSuperManageAuthHandle {

    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysAuthorityDao sysAuthorityDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @Autowired
    private SysRoleAuthDao sysRoleAuthDao;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 更新权限
     */
    public void run() {
        log.info("开始更新超管账号所有菜单+所有接口权限");
        // 获取超管角色
        SysRole role = sysRoleService.findSuperManage();
        // 获取所有菜单
        List<SysMenu> menus = sysMenuDao.list(new LambdaQueryWrapper<SysMenu>().select(SysMenu::getId));
        List<String> menuIds = menus.stream().map(SysMenu::getId).toList();
        // 获取所有权限
        List<SysAuthority> auths = sysAuthorityDao.list(new LambdaQueryWrapper<SysAuthority>().select(SysAuthority::getId));
        List<String> authIds = auths.stream().map(SysAuthority::getId).toList();
        // 开始分配
        if (menuIds.size() > 0) {
            sysRoleMenuDao.updRoleMenus(role.getId(), menuIds);
        }
        if (authIds.size() > 0) {
            sysRoleAuthDao.updRoleAuths(role.getId(), authIds);
        }
        // 清除角色权限缓存
        sysRoleService.delAuthCacheByRoleCode(role.getCode());
        log.info("已更新超管账号所有菜单, 共{}个菜单权限", menuIds.size());
        log.info("已更新超管账号所有权限, 共{}个接口权限", authIds.size());
    }
}
